package com.example.nowcodercommunity.aspect;

import com.example.nowcodercommunity.util.CommunityUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;

@Component
@Aspect
public class ServiceLogAspect {

    private Logger logger = LoggerFactory.getLogger(ServiceLogAspect.class);

    /**
     * 注解中，第一个*为返回值类型
     * com.example.nowcodercommunity.service为包名，表示我们的切入点考虑的类范围
     * .*表示全部类
     * .*(..)表示全部方法且任意输入
     *
     * 此方法相当于所有execution中涵盖方法的invoke()方法，也就是切入点
     */
    @Pointcut("execution(* com.example.nowcodercommunity.service.*.*(..))")
    public void pointCut(){}

    @Before("pointCut()")
    public void before(JoinPoint joinPoint){
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if(attributes == null){
            return;
        }
        HttpServletRequest request = attributes.getRequest();

        String IPAddress = request.getRemoteHost();
        String now = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());

        String classAndMethodName = joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName();

        logger.info(String.format("用户IP[%s] 于时间[%s] 访问了[%s]",IPAddress,now,classAndMethodName));

    }
}
